<template>
  <div class="search-result-container">
    <!-- 移除了固定的导航栏，使用Search.vue的导航栏 -->

    <div class="result-content">
      <!-- 搜索结果列表 -->
      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
      >
        <div v-for="item in list" :key="item.id" class="result-item">
          <div class="item-image">
            <img :src="item.image" alt="商品图片" />
          </div>
          <div class="item-info">
            <div class="item-title">{{ item.title }}</div>
            <div class="item-price">¥{{ item.price }}</div>
          </div>
        </div>
      </van-list>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

// 接收从父组件传递的keyword和back回调
const props = defineProps({
  keyword: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['back'])

const loading = ref(false)
const finished = ref(false)
const list = ref([])

// 监听keyword变化，重新加载数据
watch(() => props.keyword, () => {
  list.value = []
  finished.value = false
  loading.value = false
  onLoad()
})

const onLoad = () => {
  // 如果已经加载完成，不再加载
  if (finished.value) return

  // 模拟加载数据
  loading.value = true
  setTimeout(() => {
    for (let i = 0; i < 10; i++) {
      list.value.push({
        id: list.value.length + i + 1,
        title: `${props.keyword} 商品 ${list.value.length + i + 1}`,
        price: (Math.random() * 1000).toFixed(2),
        image: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
      })
    }

    loading.value = false
    if (list.value.length >= 40) {
      finished.value = true
    }
  }, 1000)
}

// 初始加载数据
onMounted(() => {
  onLoad()
})
</script>

<style scoped>
.search-result-container {
  min-height: 100%;
  background: #f7f8fa;
}

.result-content {
  padding: 12px;
}

.result-item {
  display: flex;
  padding: 12px;
  margin-bottom: 12px;
  background: white;
  border-radius: 8px;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 12px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-title {
  font-size: 14px;
  color: #323233;
  line-height: 1.4;
}

.item-price {
  font-size: 16px;
  font-weight: bold;
  color: #ee0a24;
}
</style>